﻿using DrawTools.Utils;
using LS.Screening.UI.Common;
using System;
using System.IO;
using System.Windows.Media.Imaging;

namespace LS.DicomViewer.Common
{
    public class DicomInfo
    {
        public static readonly string ImgFilePix = ".jpeg";
        public BitmapSource ImageSource => GetImageSource();

        /// <summary>
        /// dicom文件是否进行过编码压缩的，如果是，则在读取图片时，从图片缓存中读取
        /// </summary>
        public bool IsEncapsulated { get; set; }

        public string InstanceUid { get; set; }

        /// <summary>
        /// 每秒显示帧率
        /// </summary>
        public int DisplayFrameRate { get; set; } = 12;

        /// <summary>
        /// Dicom文件图片所在目录
        /// </summary>
        public string ImageFilesDir { get; set; }

        /// <summary>
        /// 像素比
        /// </summary>
        public double PixelRate { get; set; }

        int numberofFrames = 1;
        public int NumberOfFrames
        {
            get => numberofFrames;
            set
            {
                if (value == 0) return;
                numberofFrames = value;
            }
        }

        private DicomImage dicomImage;

        public DicomImage DicomImage
        {
            get => dicomImage;
            set
            {
                dicomImage = value;
                NumberOfFrames = dicomImage.NumberOfFrames;
            }
        }

        public DicomFile DicomFile { get; set; }

        public BitmapSource GetImageSource(int index = 0)
        {
            if (NumberOfFrames == 0 || index < 0 || index > NumberOfFrames - 1) return null;
            var tempFile =  Path.Combine(ImageFilesDir , index + ImgFilePix);
            if (File.Exists(tempFile))
            {
                return TryHelper.Try(() => ReadImage(tempFile));
            }
            else
            {
                tempFile = Path.Combine(ImageFilesDir, index + ".jpeg");
            }
            if (File.Exists(tempFile))
            {
                return TryHelper.Try(() => ReadImage(tempFile));
            }
            if (DicomImage != null)
            {
                var bitmap = DicomImage.RenderImage(index).As<BitmapSource>();
                var bitmapFrame = bitmap.ToBitmapFrame();
                ImageHelper.Save(tempFile, bitmapFrame);
                return bitmap;
            }
            return null;
        }

        public void FrameToSave(int frameIndex, string filePath)
        {
            var bitmap = GetImageSource(frameIndex);
            var encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                encoder.Save(stream);
            }
        }

        private BitmapImage ReadImage(string path)
        {
            if (!File.Exists(path)) return null;
            using (var file = File.OpenRead(path))
            {
                using (var reader = new BinaryReader(file))
                {
                    try
                    {
                        byte[] bytes = reader.ReadBytes((int)file.Length);
                        reader.Close();
                        file.Close();

                        var bitmapImage = new BitmapImage();
                        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                        bitmapImage.BeginInit();
                        bitmapImage.StreamSource = new MemoryStream(bytes);
                        bitmapImage.EndInit();
                        return bitmapImage;
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
            }
        }
    }
}